package com.gitee.cheungming.goods.service;

import cn.hutool.core.util.RandomUtil;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TxtToDatabase {
    // 配置常量
    private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mall_goods";
    private static final String DB_USER = "root";
    private static final String DB_PASSWORD = "123456";
    private static final String FILE_PATH = "data/item_profile.txt";
    private static final String DELIMITER = "\t"; // 分隔符，例如"|"
    private static final int BATCH_SIZE = 10000; // 批量插入大小
    private static final int EXPECTED_COLUMNS = 6; // 期望的列数

    public static void main(String[] args) {
        TxtToDatabase importer = new TxtToDatabase();
        importer.importData();
    }

    public void importData() {
        int totalLines = 0;
        int successfulLines = 0;
        int failedLines = 0;

        try (Connection connection = DriverManager.getConnection(JDBC_URL, DB_USER, DB_PASSWORD);
             BufferedReader reader = new BufferedReader(new FileReader(FILE_PATH))) {

            String sql = "INSERT INTO `mall_goods`.`goods` (`goods_name`, `url`, `price`, `description`,`brand`,`category`, `stock`, `locked_stock`) VALUES ( ?, ?,?, ?, ?, ?,?,?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {

                List<String> batchErrors = new ArrayList<>();
                String line;
                int batchCount = 0;

                while ((line = reader.readLine()) != null) {
                    totalLines++;

                    try {
                        // 跳过空行
                        if (line.trim().isEmpty()) {
                            continue;
                        }

                        String[] data = line.split(DELIMITER, -1); // 使用-1保留尾部空值

                        // 验证数据格式
                        if (data.length != EXPECTED_COLUMNS) {
                            throw new IllegalArgumentException(
                                    String.format("列数不匹配: 期望%d列，实际%d列", EXPECTED_COLUMNS, data.length));
                        }
                        String price = data[2].trim();
                        if ("".equals(price)) {
                            price = "100.0";
                        }

                        // 设置参数
                        statement.setString(1, data[0].trim());
                        statement.setString(2, data[1].trim());
                        statement.setString(3, price);
                        statement.setString(4, data[3].trim());
                        statement.setString(5, data[4].trim());
                        statement.setString(6, data[5].trim());
                        statement.setString(7, String.valueOf(RandomUtil.randomInt(1, 100)));
                        statement.setString(8, "0");

                        statement.addBatch();
                        batchCount++;
                        successfulLines++;

                        // 批量执行
                        if (batchCount % BATCH_SIZE == 0) {
                            executeBatch(statement, batchErrors);
                            connection.commit();
                            batchCount = 0;
                        }

                    } catch (Exception e) {
                        failedLines++;
                        String errorMsg = String.format("第%d行处理失败: %s - 数据: %s",
                                totalLines, e.getMessage(), line);
                        batchErrors.add(errorMsg);
                        System.err.println(errorMsg);
                    }
                }

                // 执行剩余的批次
                if (batchCount > 0) {
                    executeBatch(statement, batchErrors);
                }

                // 输出处理结果
                printImportResult(totalLines, successfulLines, failedLines);

            } catch (SQLException e) {
                throw new RuntimeException("批量插入失败", e);
            }

        } catch (IOException | SQLException e) {
            throw new RuntimeException("数据导入失败", e);
        }
    }

    private void executeBatch(PreparedStatement statement, List<String> errors) throws SQLException {
        try {
            int[] results = statement.executeBatch();
            statement.clearBatch();

            // 检查是否有失败的插入
            for (int i = 0; i < results.length; i++) {
                if (results[i] == PreparedStatement.EXECUTE_FAILED) {
                    errors.add("批量插入中第 " + (i + 1) + " 条记录插入失败");
                }
            }

        } catch (SQLException e) {
            statement.clearBatch();
            throw new SQLException("批量执行失败: " + e.getMessage(), e);
        }
    }

    private void printImportResult(int total, int success, int failed) {
        System.out.println("====== 数据导入结果 ======");
        System.out.println("总行数: " + total);
        System.out.println("成功插入: " + success);
        System.out.println("失败行数: " + failed);
        System.out.println("成功率: " + String.format("%.2f%%", (double) success / total * 100));

        if (failed > 0) {
            System.out.println("请注意检查失败的行并手动处理");
        } else {
            System.out.println("所有数据已成功插入数据库！");
        }
    }
}
